﻿/******************************************************************************
 * This file is part of libemb.
 *
 * libemb is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * libemb is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with libemb.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Project: Embedme
 * Author : FergusZeng
 * Email  : cblock@126.com
 * git	  : https://git.oschina.net/cblock/embedme
 * Copyright 2014 @ ShenZhen ,China
*******************************************************************************/

#include <iostream>
#include "Tracer.h"
#include "CommandPipe.h"

/**
 *  \brief  执行命令并取得命令输出字符串.
 *  \param  cmd 命令字符串.
 *  \param  result 命令输出.
 *  \return 命令执行成功返回STATUS_OK,命令执行失败返回STATUS_ERROR.
 */
int CommandPipe::execute(std::string cmd, std::string& result)
{
	FILE* fp = popen(cmd.c_str(),"r");
	if (NULL==fp)
	{
		TRACE_ERR("CommandPipe::execute(%s), popen failed.\n",cmd.c_str());
		return STATUS_ERROR;
	}
    result.clear();
    while(1)
    {
        char buf[256]={0};
        int ret = fread(buf, 1, sizeof(buf), fp);
        if (ret<=0) {
            break;
        }
        result += std::string(buf,ret);
    }
	pclose(fp);
	return STATUS_OK;
}

/**
 *  \brief  执行命令并取得命令输出字符串.
 *  \param  cmd 命令字符串.
 *  \return 成功返回命令输出,失败返回空字符串.
 */
std::string CommandPipe::execute(std::string cmd)
{
    std::string result="";
	FILE* fp = popen(cmd.c_str(),"r");
	if (NULL==fp)
	{
		TRACE_ERR("CommandPipe::execute(%s), popen failed.\n",cmd.c_str());
		return result;
	}
    while(1)
    {
        char buf[256]={0};
        int ret = fread(buf, 1, sizeof(buf), fp);
        if (ret<=0) {
            break;
        }
        result += std::string(buf,ret);
    }
	pclose(fp);
	return result;
}